import { VxeUI } from 'vxe-pc-ui';
import router from '@/router';
import { useRoute } from 'vue-router';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import { useComponentState } from '@/composables/useComponentState';
import { useTableResize } from '@/composables/useTableResize';
import { hasAuth } from '@/plugins/permission';
import { useTagsViewStore } from '@/store';
import { useVxeGridUtils } from '@/composables/useVxeGridUtils';
import { useClipboard } from '@vueuse/core';
import { get, set } from '@vueuse/core';

export const useTable = (options) => {
  const {
    API, // 后端API
    tableId, // 表格ID
    customConfig = {}, // 自定义配置
  } = options;

  // 表格引用
  const gridRef = ref(); // vxe-grid 组件实例
  const gridOptions = ref({}); // vxe-grid 配置
  const gridEvents = ref({}); // vxe-grid 事件

  // 附属组件引用和状态
  const addRef = ref(); // 新增
  const updateRef = ref(); // 修改
  const detailRef = ref(); // 详情

  // 公共变量
  const selectOption = ref({}); // 选择框字典数据
  const showSearch = ref(false); // 是否显示搜索表单
  const {
    isLayoutDisabled, // 布局禁用状态
    isSelectionMode, // 弹窗或者跳转组件的选择模式
    isCheckboxMode, // 多选模式
    isChildrenMode, // 子组件模式
  } = useComponentState();
  const {
    tableHeight, // 表格高度
    formItemSpan, // 表单项栅格
  } = useTableResize(isLayoutDisabled);

  // 路由相关
  const route = useRoute(); // 当前路由
  const tagsViewStore = useTagsViewStore(); // 标签页
  const utils = useVxeGridUtils(); // 相关工具函数
  const { renderToolbarButton, renderToolbarTool, generateCode } =
    useVxeGridUtils(); // 渲染工具栏按钮
  const { copy, copied } = useClipboard();

  // 选中的行数
  const selectedCount = computed(() => {
    const checkboxCount = gridRef.value?.getCheckboxRecords().length;
    const radioCount = gridRef.value?.getRadioRecord() ? 1 : 0;
    const count =
      checkboxCount == 0 ? (radioCount == 0 ? 0 : radioCount) : checkboxCount;
    return count;
  });

  // 获取选中的行
  const selectedRows = computed(() => {
    const checkboxRows = gridRef.value?.getCheckboxRecords();
    const radioRow = gridRef.value?.getRadioRecord();
    const rows = checkboxRows.length > 0 ? checkboxRows : [radioRow];
    return rows;
  });

  // 当前行数据
  const currentRow = computed(() => {
    return selectedRows.value[0];
  });

  // 是接口应用
  const isApi = computed(() => {
    return route.query.app == 'api';
  });

  // ==================== 操作处理函数 ====================
  const useActionHandle = () => {
    const actions = {
      // add
      addHandle() {
        addRef.value?.show();
      },
      // update
      updateHandle(row) {
        updateRef.value.show(row.id);
      },
      // detail
      detailHandle(row) {
        detailRef.value.show(row.id);
      },
      // delete
      deleteHandle(params) {
        const rows = Array.isArray(params) ? params : [params];
        const ids = rows.map((item) => item.id);
        const confirmMessage = $t('common.message.confirm.general', {
          default: '您确定要执行',
          params: {
            action: $t('common.action.delete', '删除'),
          },
        });
        const content = `${confirmMessage} ：${ids.join(', ')}`;
        VxeUI.modal.confirm(content).then((result) => {
          if (result === 'confirm') {
            API.delete({ id: ids }).then(() => {
              gridRef.value.commitProxy('query');
            });
          }
        });
      },

      // 生成代码
      async genCodeHandle() {
        generateCode(API, isApi.value, route);
      },

      // 方法管理
      actionHandle(row) {
        const target = $t('menu.dev.action.title', '方法管理');
        const menu = route.query.menu;
        const tag = `【${menu}-${target}】`;
        router.push({
          path: '/dev/action',
          name: 'DevAction',
          query: {
            _parent: '/dev/field',
            id: route.query.id,
            app: route.query.app,
            menu,
            tag,
          },
        });
      },
    };
    return actions;
  };
  // ==================== 列配置 ====================
  const useColumn = () => {
    const actions = useActionHandle();
    // 字段列
    const fieldColumn = computed(() => {
      if (!isApi.value) {
        return [
          {
            field: 'id',
            title: $t('common.field.id', '编号'),
            width: 50,
            align: 'center',
          },
          {
            field: 'title',
            title: $t('menu.dev.field.field.title', '字段标题'),
            align: 'left',
            width: 150,
            editRender: {
              name: 'ElInput',
            },
          },
          {
            field: 'field',
            title: $t('menu.dev.field.field.field', '字段'),
            align: 'left',
            width: 150,
          },
          {
            field: 'config.field_type',
            title: $t('menu.dev.field.field.field_type', '表字段类型'),
            align: 'left',
            width: 130,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_field_options',
            },
          },
          {
            field: 'config.type',
            title: $t('menu.dev.field.field.type', '类型'),
            align: 'left',
            width: 130,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_admin_form_options',
            },
          },
          {
            field: 'config.grid_search',
            title: $t('menu.dev.field.field.grid_search', '搜索配置'),
            align: 'left',
            width: 130,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_search',
            },
          },
          {
            field: 'config.form_post',
            title: $t('menu.dev.field.field.form_post', '表单录入'),
            align: 'left',
            width: 100,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'switch_options',
            },
          },
          {
            field: 'config.grid_visible',
            title: $t('menu.dev.field.field.grid_visible', '显示字段'),
            align: 'left',
            width: 100,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_grid_visible',
            },
          },
          {
            field: 'config.grid_width',
            title: $t('menu.dev.field.field.grid_width', '宽度'),
            align: 'left',
            width: 100,
            editRender: {
              name: 'ElInput',
            },
          },
          {
            field: 'remark',
            title: $t('common.field.remark', '备注'),
            align: 'left',
            showOverflow: 'tooltip',
            editRender: {
              name: 'ElInput',
            },
          },
          {
            field: 'status',
            title: $t('common.field.status', '状态'),
            align: 'center',
            editRender: {
              enabled: hasAuth('dev:field:modify'),
              name: 'RaDictSwitchRender',
              code: 'status_options',
            },
            width: 90,
          },
          {
            field: 'sort',
            title: $t('common.field.sort', '排序号'),
            width: 70,
            sortable: true,
            dragSort: hasAuth('dev:field:drag'),
          },

          // 结束
        ];
      } else {
        return [
          {
            field: 'id',
            title: $t('common.field.id', '编号'),
            width: 50,
            align: 'center',
          },
          {
            field: 'title',
            title: $t('menu.dev.field.field.title', '标题'),
            align: 'left',
          },
          {
            field: 'field',
            title: $t('menu.dev.field.field.field', '字段名'),
            align: 'left',
          },
          {
            field: 'config.field_type',
            title: $t('menu.dev.field.field.field_type', '字段类型'),
            align: 'left',
            visible: true,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_field_options',
            },
          },
          {
            field: 'config.type',
            title: $t('menu.dev.field.field.type', '类型'),
            align: 'left',
            visible: true,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_admin_form_options',
            },
          },
          {
            field: 'config.grid_search',
            title: $t('menu.dev.field.field.grid_search', '搜索'),
            align: 'left',
            visible: true,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'sys_search',
            },
          },
          {
            field: 'config.form_post',
            title: $t('menu.dev.field.field.form_post', '录入'),
            align: 'left',
            visible: true,
            cellRender: {
              name: 'RaDictSelectRender',
              code: 'switch_options',
            },
          },
          {
            field: 'remark',
            title: $t('common.field.remark', '备注'),
            align: 'left',
            visible: false,
          },
          {
            field: 'status',
            title: $t('common.field.status', '状态'),
            align: 'center',
            editRender: {
              enabled: hasAuth('dev:field:modify'),
              name: 'RaDictSwitchRender',
              code: 'status_options',
            },
            width: 90,
          },
          {
            field: 'sort',
            title: $t('common.field.sort', '排序号'),
            width: 70,
            sortable: true,
            dragSort: hasAuth('dev:field:drag'),
          },

          // 结束
        ];
      }
    });

    // 操作按钮
    const actionButtons = [
      {
        content: $t('common.action.update', '修改'),
        type: 'warning',
        icon: 'Edit',
        text: true,
        visible: hasAuth('dev:field:update'),
        onClick: (row) => actions.updateHandle(row),
      },
      {
        content: $t('common.action.detail', '详情'),
        type: 'info',
        icon: 'View',
        text: true,
        visible: hasAuth('dev:field:detail'),
        onClick: (row) => actions.detailHandle(row),
      },

      // 结束
    ];

    // 操作列
    const actionColumn = [
      {
        field: 'operation',
        title: $t('common.field.operation', '操作栏'),
        width: 200,
        align: 'center',
        fixed: 'right',
        visible: true,
        cellRender: {
          name: 'RaElButtonSetRender',
          buttons: actionButtons,
        },
      },

      // 结束
    ];

    // 使用 computed 属性来响应式地合并列配置
    const mergedColumns = computed(() => {
      let selectType = 'checkbox';
      if (isSelectionMode.value && !isCheckboxMode.value) {
        selectType = 'radio';
      }
      const selectionColumn = [
        { field: 'selection', type: selectType, width: 50, align: 'center' },
      ];

      if (isSelectionMode.value) {
        return [...selectionColumn, ...fieldColumn.value];
      } else {
        return [...selectionColumn, ...fieldColumn.value, ...actionColumn];
      }
    });

    return mergedColumns;
  };

  /**
   * 表单配置
   *
   * @returns
   */
  const useFormConfig = () => {
    // 前端搜索字段配置
    const frontendData = {
      keyword: null,
      status: null,
    };

    // 前端搜索字段配置
    const frontendItems = computed(() => [
      {
        field: 'keyword',
        title: $t('common.field.keyword', '关键词'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'ElInput',
          props: {
            placeholder: $p('common.field.keyword', '关键词'),
          },
        },
      },
      {
        field: 'status',
        title: $t('common.field.status', '状态'),
        folding: true,
        resetValue: null,
        itemRender: {
          name: 'RaDictSelectRender',
          props: {
            code: 'status_options',
            placeholder: $p('common.field.status', '状态', 'select'),
          },
        },
      },

      // 结束
    ]);

    // 操作按钮
    const actionButtons = {
      folding: true,
      align: 'left',
      itemRender: {
        name: 'RaElButtonSetRender',
        props: {
          buttons: [
            {
              nativeType: 'submit',
              content: $t('common.action.search', '搜索'),
              type: 'primary',
              icon: 'Search',
            },
            {
              nativeType: 'reset',
              content: $t('common.action.reset', '重置'),
              type: 'info',
              icon: 'Refresh',
            },

            // 结束
          ],
        },
      },
    };

    // 最终提供给组件的 formConfig，使用 computed 保证响应式
    const formConfig = computed(() => {
      return {
        span: formItemSpan.value,
        collapseStatus: showSearch.value,
        titleOverflow: true,
        titleBold: true,
        data: frontendData,
        items: [...frontendItems.value, actionButtons],
      };
    });

    return frontendItems.value.length > 0 ? formConfig : {};
  };

  /**
   * 工具栏配置
   *
   * @returns
   */
  const useToolbarConfig = () => {
    const buttons = [
      {
        name: $t('common.action.back', '返回'),
        code: 'return_code',
        status: 'info',
        icon: 'Back',
        visible: computed(() => {
          return isChildrenMode.value;
        }),
      },
      {
        name: $t('common.action.add', '新增'),
        code: 'add_code',
        status: 'success',
        icon: 'Plus',
        visible: hasAuth('dev:field:add'),
      },
      {
        name: $t('common.action.update', '修改'),
        code: 'update_code',
        status: 'warning',
        icon: 'Edit',
        visible: hasAuth('dev:field:update'),
        disabled: computed(() => {
          return selectedCount.value != 1;
        }),
      },
      {
        name: $t('common.action.detail', '详情'),
        code: 'detail_code',
        status: 'info',
        icon: 'View',
        visible: hasAuth('dev:field:detail'),
        disabled: computed(() => {
          return selectedCount.value != 1;
        }),
      },
      {
        name: $t('common.action.delete', '删除'),
        code: 'delete_code',
        status: 'danger',
        icon: 'Delete',
        visible: hasAuth('dev:field:delete'),
        disabled: computed(() => {
          return selectedCount.value === 0;
        }),
      },
      {
        name: $t('common.action.gen_code', '生成'),
        code: 'gen_code_code',
        status: 'danger',
        icon: 'Select',
        plain: true,
        visible: hasAuth('dev:menu:gen_code'),
      },
      {
        name: $t('common.action.action_mgr', '方法'),
        code: 'action_code',
        status: 'default',
        icon: 'Operation',
        visible: hasAuth('dev:menu:action'),
      },

      // 结束
    ];

    const getToolbarConfig = () => {
      const toolbarConfig = {
        refresh: true,
        zoom: true,
        custom: true,
        buttons: renderToolbarButton(buttons),
        tools: [
          {
            code: 'search_code',
            circle: true,
            icon: computed(() => {
              return showSearch.value
                ? 'vxe-icon-arrow-down'
                : 'vxe-icon-arrow-up';
            }),
          },
        ],
      };
      return isSelectionMode.value ? {} : toolbarConfig;
    };

    return getToolbarConfig();
  };

  /**
   * 事件配置
   *
   * @returns
   */
  const useGridEvents = () => {
    const actions = useActionHandle();
    const events = {
      /**
       * 左侧工具栏按钮点击事件
       * @param {*} params
       */
      toolbarButtonClick(params) {
        // 根据不同code分别执行逻辑
        switch (params.code) {
          case 'return_code':
            utils.previousHandle(tagsViewStore, route, router);
            break;
          case 'add_code':
            actions.addHandle();
            break;
          case 'update_code':
            actions.updateHandle(selectedRows.value[0]);
            break;
          case 'delete_code':
            actions.deleteHandle(selectedRows.value);
            break;
          case 'detail_code':
            actions.detailHandle(selectedRows.value[0]);
            break;
          case 'action_code':
            actions.actionHandle();
            break;
          case 'gen_code_code':
            actions.genCodeHandle();
            break;
        }
      },

      /**
       * 右侧工具栏点击事件
       * @param {*} params
       */
      toolbarToolClick(params) {
        switch (params.code) {
          case 'search_code':
            showSearch.value = !showSearch.value;
            break;
        }
      },
      /**
       * 行拖拽排序
       * @param {*} event
       */
      async rowDragend(event) {
        const params = utils.getDragParams(event, gridRef.value, 'sort');
        try {
          await API.drag(params);
          gridRef.value.commitProxy('query');
        } catch (error) {
          console.error('Drag sort failed:', error);
        }
      },

      /**
       * 单元格编辑关闭事件，实现单元格编辑保存功能
       * @param {*} param
       */
      async editClosed({ row, column }) {
        function getNestedValue(obj, path) {
          const keys = path.split('.');
          return keys.reduce((currentObject, key) => {
            return currentObject && currentObject[key] !== undefined
              ? currentObject[key]
              : undefined;
          }, obj);
        }
        try {
          const fieldPath = column.field;
          const value = getNestedValue(row, fieldPath);
          await API.modify({ id: row.id, [column.field]: value });
          ElMessage.success('操作成功');
        } catch (error) {
          console.error('Edit closed failed:', error);
        }
      },

      /**
       * 单选框点选后,增加向父窗口传递参数
       * @param {*} param0
       */
      radioChange({ row }) {
        utils.radioChangeHandle(row, route);
      },

      /**
       * 复选框点选后,增加向父窗口传递参数
       * @param {*} param
       */
      checkboxChange({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },

      /**
       * 复选框的全选,增加向父窗口传递参数
       * @param {*} param
       */
      checkboxAll({ records }) {
        utils.checkBoxChangeHandle(records, route);
      },
      /**
       * 双击单元格
       */
      cellDblclick({ row, column }) {
        if (column.field !== 'remark') {
          copy(row[column.field]);
          if (copied) {
            ElMessage.success('已拷贝到剪贴板');
          }
        }
      },
    };

    return { getGridEvents: async () => events };
  };

  /**
   * 代理配置
   *
   * @returns
   */
  const useProxyConfig = () => {
    const getProxyConfig = async () => {
      return {
        sort: true,
        form: true,
        page: true,
        filter: true,
        response: {
          result: 'data',
          total: 'total',
        },
        ajax: {
          async query({ page, form, sorts, filters }) {
            // 合并表单参数和URL参数
            const queryParams = { ...form, ...route.query };
            // 排序参数
            if (sorts.length > 0) {
              queryParams.order_by = sorts
                .map((item) => `${item.field}|${item.order}`)
                .join(',');
            }
            // 分页参数
            if (page) {
              queryParams.page_size = page.pageSize;
              queryParams.current_page = page.currentPage;
            }
            // 过滤参数
            if (filters) {
              filters.map((item) => {
                queryParams[item.field] = item.values;
              });
            }
            try {
              const { data: result } = await API.index(queryParams);
              if (result.sort) {
                const sortRules = Object.entries(result.sort).map(
                  ([field, order]) => ({ field, order: order.toLowerCase() }),
                );
                gridRef.value.setSort(sortRules);
              }
              return result;
            } catch (error) {
              console.error('data loading failed:', error);
              throw error;
            }
          },
        },
      };
    };

    return { getProxyConfig };
  };

  /**
   * 主要配置函数
   */
  const columns = useColumn(); // 列配置
  const formConfig = useFormConfig(); // 表单配置
  const toolbarConfig = useToolbarConfig(); // 工具栏配置
  const { getProxyConfig } = useProxyConfig(); // 代理配置
  const { getGridEvents } = useGridEvents(); // 表格事件
  // 获取表格配置
  const getGridConfig = async () => {
    const options = {
      id: tableId,
      height: tableHeight,
      border: true,
      keepSource: false,
      rowConfig: {
        useKey: true,
        keyField: 'id',
        isHover: true,
        isCurrent: true,
        drag: true,
      },
      columnConfig: {
        resizable: true,
      },
      resizableConfig: {
        dragMode: 'fixed',
        isDblclickAutoWidth: true,
        minWidth: 60,
      },
      customConfig: {
        storage: true,
      },
      editConfig: {
        trigger: 'dblclick',
        mode: 'cell',
        showStatus: false,
      },
      printConfig: {
        excludeFields: ['selection', 'operation'],
      },
      filterConfig: {
        remote: true,
      },
      sortConfig: {
        remote: true,
      },
      columns,
      formConfig,
      toolbarConfig,
      proxyConfig: await getProxyConfig(),
      // 合并自定义配置
      ...customConfig,
    };
    // 事件
    const events = await getGridEvents();
    // 返回表格配置和事件
    return { options, events };
  };

  // 初始化表格
  const initTable = async () => {
    try {
      selectOption.value = await API.getOptions();
      const config = await getGridConfig();
      gridOptions.value = config.options;
      gridEvents.value = config.events;
    } catch (error) {
      console.error('vxe-grid initialization failed', error);
    }
  };

  return {
    // 表格引用和配置
    gridRef,
    gridOptions,
    gridEvents,
    // 附属组件的引用
    addRef,
    updateRef,
    detailRef,
    // 选择组件选项
    selectOption,
    // 初始化方法
    initTable,
  };
};
